package cn.ha.toy.web;

import java.sql.Date;
import java.text.SimpleDateFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.ha.toy.entity.User;

@Controller
@RequestMapping("valid")
public class ValidatorController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 使用WebDataBinder实现日期校验
	 * @param dataBinder
	 */
	@InitBinder
	public void dateFormat(WebDataBinder dataBinder){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,false));
	}
	
//	@Autowired
//	private UserValidator userValidator;
	@InitBinder
	private void userValidBinder(WebDataBinder dataBinder){
		logger.info("======================================");
		logger.info("userValidator");
//		dataBinder.addValidators(userValidator);
	}
	
	@RequestMapping(method={RequestMethod.POST})
	public String save(@Validated User user,BindingResult br,RedirectAttributes ra){
		logger.info("======================================");
		logger.info("addFlashAttribute");
		ra.addFlashAttribute("user",user);
		return "user";
	}
	
}
